import { createApp } from 'vue';
import App from './App.vue';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
import router from './router';
import './style.css';
import axios from 'axios';
import { ElMessage } from 'element-plus';

// 配置axios请求拦截器，统一添加JWT令牌
axios.interceptors.request.use(
  config => {
    // 检查当前是否在API文档页面，如果是则不添加token
    const currentPath = window.location.pathname;
    if (currentPath === '/api-docs') {
      // API文档页面不需要认证，不添加token
      return config;
    }
    
    const token = localStorage.getItem('token'); // 从localStorage获取令牌
    if (token) {
      config.headers.Authorization = `Bearer ${token}`; // 添加Authorization头
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器，处理token失效自动退出
axios.interceptors.response.use(
  response => response,
  error => {
    if (error.response && error.response.status === 401) {
      // 检查当前是否在API文档页面，如果是则不进行跳转
      const currentPath = window.location.pathname;
      if (currentPath === '/api-docs') {
        // API文档页面不需要登录，直接返回错误，不做任何处理
        return Promise.reject(error);
      }
      
      // 清除本地登录状态
      localStorage.removeItem('isLoggedIn');
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('rememberMe');
      
      // 跳转到登录页
      if (currentPath !== '/login') {
        setTimeout(() => {
          if (window.__VUE_ROUTER__) {
            window.__VUE_ROUTER__.push('/login');
          } else {
            window.location.href = '/login';
          }
        }, 0);
      }
      // 只用ElMessage弹窗提示
      window.ElMessage && window.ElMessage.error('登录已过期，请重新登录');
    }
    return Promise.reject(error);
  }
);

// 让全局可访问router和ElMessage
window.__VUE_ROUTER__ = router;
window.ElMessage = ElMessage;

const app = createApp(App);
app.use(ElementPlus);
app.use(router);
app.mount('#app');

